package com.example.erp.service.impl;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import com.example.erp.entity.Book;

public class RestService {

	public static List<Book> query(JSONObject jsonObject) {
		List<Book> books = new ArrayList<Book>();
		try {
			// 设置连接超时和读取超时
			Duration connectTimeout = Duration.ofSeconds(10);
			Duration responseTimeout = Duration.ofSeconds(30);
			HttpClient httpClient = HttpClient.newBuilder().connectTimeout(connectTimeout).build();
			URI uri = URI.create("http://localhost:8082/erp/RestServiceDispatcher/query");

			// 构建eiInfo2.0最小集
			jsonObject.put("__version__", "2.0");
			HttpRequest postRequest = HttpRequest.newBuilder().timeout(responseTimeout).uri(uri)
					.header("Content-Type", "application/json;charset=utf-8")
					.POST(BodyPublishers.ofString(jsonObject.toJSONString())).build();

			HttpResponse<String> postResponse = httpClient.send(postRequest, BodyHandlers.ofString());
			System.out.println("POST 同步响应码：" + postResponse.statusCode());
			System.out.println("POST 同步响应体：" + postResponse.body());
			JSONObject result = JSON.parseObject(postResponse.body().toString());
			String list = result.getString("list");
			// 转实体类型返回
			books = JSON.parseObject(list, new TypeReference<List<Book>>() {
			});
		} catch (IOException | InterruptedException ex) {
			System.err.println("RestService.call error:" + ex.getMessage());
		}
		return books;
	}

	public static int execute(JSONObject jsonObject) {
		int result = 0;
		try {
			// 设置连接超时和读取超时
			Duration connectTimeout = Duration.ofSeconds(10);
			Duration responseTimeout = Duration.ofSeconds(30);
			HttpClient httpClient = HttpClient.newBuilder().connectTimeout(connectTimeout).build();
			URI uri = URI.create("http://localhost:8082/erp/RestServiceDispatcher/execute");

			// 构建eiInfo2.0最小集
			jsonObject.put("__version__", "2.0");
			HttpRequest postRequest = HttpRequest.newBuilder().timeout(responseTimeout).uri(uri)
					.header("Content-Type", "application/json;charset=utf-8")
					.POST(BodyPublishers.ofString(jsonObject.toJSONString())).build();

			HttpResponse<String> postResponse = httpClient.send(postRequest, BodyHandlers.ofString());
			System.out.println("POST 同步响应码：" + postResponse.statusCode());
			System.out.println("POST 同步响应体：" + postResponse.body());
			JSONObject resultJson = JSON.parseObject(postResponse.body().toString());
			result = resultJson.getIntValue("result");
		} catch (IOException | InterruptedException ex) {
			System.err.println("RestService.call error:" + ex.getMessage());
		}
		return result;
	}
}
